<template>
  <div class="lineup" v-loading="loading">
    <div class="top">
      <div class="search">
        <div class="contition">
          <div class="wrap_time">
            <date-time type="other_half_hour" @changeType="changeType" :query="query" @isFold="isShowFold" :isTimePeriod = "true"></date-time>
            <el-button type="primary" class="primary_btn fr find" @click.stop='search'>{{$t('public.search2')}}</el-button>
            <div class="clear"></div></div>
          <div class="wrap_drop">
            <unfold :isShow="isFold" :title="[]">
              <template slot="unfoldSlot">
                <div class="skill">
                  <span class="ski">{{$t('public.queues')}}:</span>
                  <el-select size="mini"
                             v-model.trim="query.peerId"
                             :placeholder="$t('report.queueNaSea')"
                             multiple
                             filterable>
                    <el-option v-for="item in mailQueues"
                               :label="item.DisplayName"
                               :value="item.Exten"
                               :key="item._id"></el-option></el-select>
                </div>
              </template>
            </unfold>
          </div>
        </div>
      </div>
      <affix :label="title"></affix>
    </div>
    <div :id="id">
      <el-row class="ichars">
        <highcharts :options="highchartsOptions"></highcharts>
        <div class="notes">
          <span class="light">{{$t('report.hicharsNotes')}}: <span></span>{{$t('report.hicharsLight')}}</span>
          <span class="dark"><span></span>{{$t('report.hicharsDark')}}</span>
        </div>
      </el-row>
      <div class="tab agent_table">
        <div class="export">
          <el-button class="primary_btn fr set_header" v-show="configFormula" @click="$refs.formulaEditorDialog.open()">{{$t('report.formalTitle')}}</el-button>
          <el-button class="primary_btn fr" v-on:click.stop="isHeaderConfigShow=!isHeaderConfigShow" v-if="!configHeaderBool">{{$t('report.setHeaderConfig')}}</el-button>

          <!-- <el-button class="primary_btn fr"
            v-if="$store.getters.exportFromEnd && flag === 'kf'"
            @click.stop="exportXls"
          >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->

          <el-button class="primary_btn fr"
            v-if="flag === 'kf'"
            @click.stop="exportXlsx"
          >{{$t('report.exportXls')}}</el-button>

          <el-button class="primary_btn fr pdf" @click.stop="exportPdf">{{$t('report.exportPDF')}}</el-button>
          <!-- <el-button class="primary_btn fr pdf" v-show="isShowDetailExport" v-on:click.stop="exportXls(true)">{{$t('report.imExportDetailXls')}}
          </el-button> -->
          <el-tooltip class="item" :content="$t('report.imdetailText')" effect="dark" placement="bottom">
            <el-button class="primary_btn fr pdf" v-show="isShowDetailExport && flag === 'kf'" v-on:click.stop="exportXls(true)">{{$t('report.exportDetailXls')}}
              <span class="tip"><i class="iconfont icon-tixingweizhi"></i></span>
            </el-button>
          </el-tooltip>
        </div>
        <div class="deploy">
          <el-collapse accordion>
            <el-collapse-item>
              <template slot="title">
                <span class="fl explain">{{$t('report.toggleInstructe')}}</span>
              </template>
              <div>
                1. {{$t('report.imQueueLineUpAllNum')}} <br>
                2. {{$t('report.imQueueAccessNum')}} <br>
                3. {{$t('report.queueGiveUpCount')}} <br>
                4. {{$t('report.imQueueGiveUpLineFiveNum')}} <br>
                5. {{$t('report.imQueueGiveUpFiveTenNum')}} <br>
                6. {{$t('report.imQueueAvgAccesTime')}} <br>
                7. {{$t('report.imQueueMaxAcessTime')}} <br>
                8. {{$t('report.imQueueAvgGiveUpTime')}} <br>
                9. {{$t('report.imQueueMaxGiveUpTime')}} <br>
                10. {{$t('report.imQueueMinGiveUpTime')}} <br>
                11. {{$t('report.imQueueAccessRate')}} <br>
                12. {{$t('report.imQueueGiveUpEvalute')}} <br>
                13. {{$t('report.SessionTimeTrendTableOne')}} <br>
                <p class="custom_alg">{{$t('report.ziDingYi')}}：</p>
                <p v-for="(item, index) in formulas" :key="item.name">
                  {{index + 14}}.{{item.formulaInstr}}
                </p>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <report-table :data="tableData" :sum="totalData" :config="[...headOptions.Config,  ...formulasConfig]"></report-table>
      </div>
    </div>
    <!-- 自定义公式组件 -->
    <FormulaEditorDialog ref="formulaEditorDialog" :headOptionsConfig="headOptions.Config" @closeFormulaDialog="closeFormulaDialog" reportName="排队情况" :reportType="id"/>
    <header-option v-show="isHeaderConfigShow" :headCustom="formulasConfig" :show="isHeaderConfigShow" :option="headOptionsShow" :type="id" v-on:close="close"></header-option>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
      <span>{{$t('report.reportExportTipTitle')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
        <el-button type="primary" class="primary_btn" @click="confirm">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import affix from '../../../ui-modules/affix/Affix.vue'
  import unfold from '../../../ui-modules/unfold/index.vue'
  import dateTime from '../base/datetime.vue'
  import reportTable from '../base/reportTable.vue'
  import headerOption from '../base/headerOption.vue'
  import { deepClone, getFormatTimeBySecond, optionTimeTypeCheck, isHasFunc } from '@/utils/m7Utils.js'
  import { exportReportPdf, headOptionsToXlsxHeaders, checkTime, searchTime, colorConfigArr, mixData } from '@/utils/reportUtils.js'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
  import FormulaEditorDialog from '../base/FormulaEditorDialog.vue'
  export default {
    name: 'lineup',
    data () {
      return {
        configFormula: true, // 自定义公式的权限
        highchartsOptions: {},
        tableData: [],
        totalData: [],
        flag: this.$store.getters.isEcommerce ? 'ecommerce' : 'kf',
        dateType: 'day', // 当前选择时间类型
        dialogVisible: false,
        loading: false,
        isFold: false,
        mailQueues: [],
        query: {
          peerId: []
        },
        serverData: [],
        title: this.$t('report.imReportQueueLineUp'),
        highchartsDefaultOptions: {
          chart: { type: 'column', animation: false },
          colors: colorConfigArr,
          xAxis: {
            categories: [],
            title: {
              enabled: true,
              text: '',
              style: { fontWeight: 'normal' }
            }
          },
          yAxis: {
            gridLineColor: '#e6e6e6',
            allowDecimals: false,
            title: { text: '' },
            showEmpty: false
          },
          title: {text: this.$t('report.imReportQueueLineUp')},
          legend: { align: 'center', verticalAlign: 'top', y: 30 },
          tooltip: {
            pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}{point.valueSuffix}</b><br/>',
            shared: true
          },
          credits: { enabled: false },
          series: []
        },
        isHeaderConfigShow: false,
        headOptionsShow: { Config: [], data: [] },
        headOptions: { Config: [], data: [] },
        id: 'cc_im_topeer_wait_report',
        isSearch: false,
        formulas: [] // 公式数据
      }
    },
    components: {
      affix,
      unfold,
      dateTime,
      headerOption,
      reportTable,
      FormulaEditorDialog
    },
    watch: {
      // 监测自定义公式变化 更新数据
      formulas (cur, old) {
        if (this.isSearch) {
          return
        }
        if (!this.serverData || this.serverData.length === 0) {
          return
        }
        this.serverData = mixData(deepClone(this.serverData), this.formulas)
        this.highchartsOptions = this.getHighchartsOptions()
        this.tableData = this.getTableData(this.serverData, this.headOptions)
        this.totalData = this.getTotalData(this.serverData, this.headOptions)
      }
    },
    methods: {
      // 自定义公式弹窗关闭外抛事件
      closeFormulaDialog () {
        this.isSearch = false
        this.$store.dispatch('queryFetchFormula', {type: this.id}).then((resp) => {
          if (resp.success) {
            this.formulas = resp.data.Formulas
          }
        })
      },
      // 子组件切换时间类型传上来得方法 触发计算属性
      changeType (type) {
        this.dateType = type
      },
      // 处理合计
      getTotalData (serverData, headOptions) {
        if (!serverData || serverData.length === 0) {
          return [{peerId: this.$t('report.total')}]
        }

        let headerConfig = headOptions.Config || []
        let datas = serverData
        let total = {
          peerId: this.$t('report.total'),
          queueGiveupTotalTimeLength: 0,
          queueAccessTotalTimeLength: 0
        }

        for (let i = 0; i < headerConfig.length; i++) {
          for (let j = 0; j < datas.length; j++) {
            if (!isNaN(datas[j][headerConfig[i].name])  && headerConfig[i].name !== 'peerId') {
              if ((headerConfig[i].name in total) === false) {
                total[headerConfig[i].name] = 0
              }
              if (headerConfig[i].name === 'maxQueueAccessTimeLength' || headerConfig[i].name === 'maxQueueGiveupTimeLength') {
                if (datas[j][headerConfig[i].name] > total[headerConfig[i].name]) {
                  total[headerConfig[i].name] = datas[j][headerConfig[i].name]
                }
              } else if (headerConfig[i].name === 'minQueueGiveupTimeLength') {
                if (j === 0) {
                  total[headerConfig[i].name] = datas[j][headerConfig[i].name]
                }
                if (datas[j][headerConfig[i].name] < total[headerConfig[i].name]) {
                  total[headerConfig[i].name] = datas[j][headerConfig[i].name]
                }
              } else {
                total[headerConfig[i].name] += datas[j][headerConfig[i].name]
              }
              if (headerConfig[i].name === 'queueAccessAvgTimeLength') {
                total.queueGiveupTotalTimeLength += datas[j]['queueGiveupTotalTimeLength']
              } else if (headerConfig[i].name === 'queueGiveupAvgTimeLength') {
                total.queueAccessTotalTimeLength += datas[j]['queueAccessTotalTimeLength']
              }
            }
          }
        }
        // 接入率
        total.accessRate = total.queueCount > 0 ? (total.queueAccessCount / total.queueCount * 100).toFixed(1) + '%' : '0.0%'
        // 放弃率
        total.queueGiveupRate = total.queueCount > 0 ? ((total.queueGiveupCount + total.noAccessCount) / total.queueCount * 100).toFixed(1) + '%' : '0.0%'
        // 平均接入时长
        total.queueAccessAvgTimeLength = total.queueAccessCount > 0 ? Math.round(total.queueAccessTotalTimeLength / total.queueAccessCount) : 0
        // 平均放弃时长
        total.queueGiveupAvgTimeLength = total.queueGiveupCount > 0 ? Math.round(total.queueGiveupTotalTimeLength / total.queueGiveupCount) : 0
        total = mixData([total], this.formulas)[0]
        headOptions.Config.forEach((option, index) => {
          if (option.timeType && option.timeType === 'hhmmss') {
            total[option.name] = getFormatTimeBySecond(total[option.name])
          } else if (option.timeType && option.timeType === 'second') {
            total[option.name] = Math.round(total[option.name]) + 's'
          }
        })
        return [total]
      },
      getTableData (serverData, headOptions) {
        if (!this.serverData || this.serverData.length === 0) {
          return []
        }
        let data = deepClone(this.serverData)
        data.forEach(item => {
          item.peerId = this.getPeerIdName(item.peerId)
          this.headOptions.Config.forEach((option, index) => {
            item[option.name] = item[option.name] ? item[option.name] : 0
            if (option.name.indexOf('Rate') > -1 && option.displayname.indexOf('率') > -1) {
              item[option.name] = `${item[option.name]}%`
            }
            if (option.timeType && option.timeType === 'hhmmss') {
              item[option.name] = getFormatTimeBySecond(item[option.name])
            } else if (option.timeType && option.timeType === 'second') {
              item[option.name] = item[option.name] + 's'
            }
          })
        })
        return data
      },
      getPeerIdName (id) {
        for (var i = 0; i < this.mailQueues.length; i++) {
          if (this.mailQueues[i].Exten === id) {
            return this.mailQueues[i].DisplayName
          }
        }
        return id
      },
      confirm () {
        this.dialogVisible = false
        exportReportPdf({title: this.$t('report.webchat') + this.title + searchTime(this.query), id: this.id})
      },
      close (data) {
        if (data) {
          this.search()
        }
        this.isHeaderConfigShow = false
      },
      exportPdf () {
        this.dialogVisible = true
      },
      isShowFold (bool) {
        this.isFold = bool
      },
      getSearchQueryData () {
        let data = {
          reportType: this.id,
          account: this.$store.state.session.user.account,
          query: { reportType: this.id }
        }
        let query = deepClone(this.query)
        if (query.timeType === 'other_half_hour') {
          let message = checkTime(query.StartTime, query.EndTime, false, false) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        data.query = Object.assign({}, data.query, query)
        return data
      },
      search () {
        let queryData = this.getSearchQueryData()
        if (!queryData) {
          return
        }
        this.loading = true
        this.$store.dispatch('queryImToPeerQueueReport', queryData).then((res) => {
          if (this.$store.state.report.customExportData) {
            res = JSON.parse(this.$store.state.report.customExportData)
          }
          this.isSearch = true
          this.$store.dispatch('queryFetchFormula', {type: this.id}).then((resp) => {
            if (resp.success) {
              this.loading = false
              this.formulas = resp.data.Formulas
              // 表头
              this.headOptions = optionTimeTypeCheck(deepClone(res.tableHeader) || this.headOptions)
              this.headOptionsShow = optionTimeTypeCheck(deepClone(res.tableHeader) || this.headOptionsShow)
              this.serverData = deepClone(mixData(res.data, this.formulas)) || deepClone(mixData(this.serverData, this.formulas))
              this.highchartsOptions = this.getHighchartsOptions()
              this.tableData = this.getTableData(this.serverData, this.headOptions)
              this.totalData = this.getTotalData(this.serverData, this.headOptions)
            }
          })
        })
      },
      exportXls (bool) {
        let data = {
          Method: 'exportTopeerQueueReport',
          Query: { reportType: this.id, user: this.$store.state.session.user._id }
        }
        // 导出详细excel更改method
        if (bool === true) {
          data.Method = 'exportTopeerQueueReportDetail'
        }
        let query = deepClone(this.query)
        if (query.timeType === 'other') {
          let message = checkTime(query.StartTime, query.EndTime, false, true) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
          let StartTimeStr = query.StartTime.replace(/-/g, '')
          query.StartTime = StartTimeStr
          let EndTimeStr = query.EndTime.replace(/-/g, '')
          query.EndTime = EndTimeStr
        }
        data.Query = Object.assign({}, data.Query, query)
        this.$store.dispatch('exportBusinessAnalyseReport', data)
      },
      exportXlsx () {
        let queryData = this.getSearchQueryData()
        if (!queryData) {
          return
        }
        this.$store.dispatch('queryImToPeerQueueReport', queryData).then((res) => {
          if (this.$store.state.report.customExportData) {
            res = JSON.parse(this.$store.state.report.customExportData)
          }
          // 表头
          let headOptions = optionTimeTypeCheck(deepClone(res.tableHeader) || this.headOptions)
          let serverData = mixData(deepClone(res.data), this.formulas) || []
          let tableData = this.getTableData(serverData, headOptions)
          if (tableData && tableData.length) {
            var sum = this.getTotalData(serverData, headOptions)
            tableData = tableData.concat(sum)
          }
          let headers = headOptionsToXlsxHeaders([...headOptions.Config, ...this.formulasConfig])

          let dh = XlsxUtil.getDownloadHelper(headers, tableData)
          let timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
          dh.download(this.$t('report.imReportQueueLineUp') + timeStamp)
        })
      },
      getHighchartsOptions () {
        let options = deepClone(this.highchartsDefaultOptions)
        if (!this.serverData || this.serverData.length === 0) {
          return options
        }

        let headerConfig = this.headOptions.Config || []
        let datas = this.serverData
        let categoriesArray = []
        let seriesArray = []

        headerConfig.forEach(item => {
          if (!item.show) {
            return
          }
          if (item.name === 'peerId' || item.name.indexOf('TimeLength') > -1 || item.name.indexOf('Rate') > -1) {
            return
          }
          let serie = { name: item.displayname, data: [], valueName: item.name }
          seriesArray.push(serie)
        })

        for (let i = 0; i < datas.length; i++) {
          categoriesArray.push(this.getPeerIdName(datas[i].peerId))
          for (let j = 0; j < seriesArray.length; j++) {
            seriesArray[j].data.push(parseFloat(datas[i][seriesArray[j].valueName]))
          }
        }

        options.xAxis.categories = categoriesArray
        options.series = seriesArray

        return options
      }
    },
    computed: {
      // 自定义表头
      formulasConfig () {
        return this.formulas.map((d, i) => {
          return {
            displayname: d.displayname,
            name: d.name,
            order: d.order,
            show: d.show,
            timeType: 'none',
            digits: d.digits,
            type: d.type
          }
        })
      },
      // 是否展示导出详细excel
      isShowDetailExport () {
        let type = ['month']
        return type.includes(this.dateType)
      },
      configHeaderBool () {
        return this.$store.state.report.setConfigHeaderBool
      }
      // totalData () {
      //   return this.getTotalData(this.serverData, this.headOptions)
      // },
      // tableData () {
      //   return this.getTableData(this.serverData, this.headOptions)
      // },
      // highchartsOptions () {
      //   let options = deepClone(this.highchartsDefaultOptions)
      //   if (!this.serverData || this.serverData.length === 0) {
      //     return options
      //   }
      //
      //   let headerConfig = this.headOptions.Config || []
      //   let datas = this.serverData
      //   let categoriesArray = []
      //   let seriesArray = []
      //
      //   headerConfig.forEach(item => {
      //     if (!item.show) {
      //       return
      //     }
      //     if (item.name === 'peerId' || item.name.indexOf('TimeLength') > -1 || item.name.indexOf('Rate') > -1) {
      //       return
      //     }
      //     let serie = { name: item.displayname, data: [], valueName: item.name }
      //     seriesArray.push(serie)
      //   })
      //
      //   for (let i = 0; i < datas.length; i++) {
      //     categoriesArray.push(this.getPeerIdName(datas[i].peerId))
      //     for (let j = 0; j < seriesArray.length; j++) {
      //       seriesArray[j].data.push(parseFloat(datas[i][seriesArray[j].valueName]))
      //     }
      //   }
      //
      //   options.xAxis.categories = categoriesArray
      //   options.series = seriesArray
      //
      //   return options
      // }
    },
    beforeMount () {
      if (isHasFunc('func_forbid_config_formula', this.$store.state.session.user)) {
        this.configFormula = false // 没有自定义公式的配置权限
      }
      this.$store.dispatch('getDicCache', {type: 'mailQueues'}).then((res) => {
        if (res && res.success) {
          this.mailQueues = res.data
        }
        this.search()
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .lineup
    .set_header
      margin-left 10px
    .tip
      cursor pointer
      display inline-block
      height 16px
      width 16px
      border 1px solid $c-main
      text-align center
      line-height 15px
      border-radius 50%
      margin 0px 0 0 6px
      .iconfont
        border none
        font-size 10px
        color $c-main
    .skill
      margin-top 14px
      .ski
        margin-right 20px
</style>
